import SwiftUI

// 常用词分组模型
struct PhraseGroup: Identifiable, Codable {
    let id: Int
    let name: String
}

// 常用词模型
struct Phrase: Identifiable,Codable {
    let id: Int
    let groupId: Int
    let content: String
}

// 对话模型
struct DialogItem: Codable {
    let id: String
    let content: String
}

struct KeyboardView: View {
    let proxy: UITextDocumentProxy
    
    // 键盘模式
    enum KeyboardMode {
        case phrases     // 常用词模式
        case dialog      // 语境对话模式
    }
    @State private var keyboardMode: KeyboardMode = .phrases
    @State private var shiftEnabled = false
    @State private var currentText = ""
    @State private var candidates = [String]()
    
    // 常用词相关状态
    @State private var phraseGroups = [PhraseGroup]() // 从服务器获取的分组
    @State private var phrases = [Phrase]() // 从服务器获取的常用词列表
    @State private var allPhrases = [Phrase]() // 从服务器获取的常用词列表
    @State private var selectedGroupId: Int? = nil // 当前选中的分组ID
    
    // 语境对话相关状态
    @State private var dialogItems = [DialogItem]() // 从服务器获取的对话列表
    @State private var currentDialog = "" // 当前选中的对话内容
    
    
    var body: some View {
        VStack(spacing: 8) {
            // 顶部功能按钮
            HStack {
                Button(action: {
                    keyboardMode = .phrases
                    if phraseGroups.isEmpty {
                        loadMockData() // 首次加载模拟数据
                    }
                }) {
                    Text("常用词")
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 8)
                        .background(keyboardMode == .phrases ? Color.blue.opacity(0.3) : Color(.systemGray5))
                        .cornerRadius(5)
                        .foregroundColor(.black)
                }
                .buttonStyle(PlainButtonStyle())
                
                Button(action: {
                    keyboardMode = .dialog
                    if dialogItems.isEmpty {
                        loadMockData() // 首次加载模拟数据
                    }
                }) {
                    Text("语境对话")
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 8)
                        .background(keyboardMode == .dialog ? Color.blue.opacity(0.3) : Color(.systemGray5))
                        .cornerRadius(5)
                        .foregroundColor(.black)
                }
                .buttonStyle(PlainButtonStyle())
            }
            .padding(.horizontal, 5)
            
            // 使用 GeometryReader 计算最大高度
            GeometryReader { geometry in
                VStack(spacing: 8) {
                    if keyboardMode == .phrases {
                        phrasesView
                            .frame(height: maxHeight) // 绑定最大高度
                    } else if keyboardMode == .dialog {
                        dialogView
                            .frame(height: maxHeight) // 绑定最大高度
                    }
                }
                .onAppear {
                    // 动态计算最大高度
                    let phrasesHeight = geometry.size.height
                    let dialogHeight = geometry.size.height
                    maxHeight = max(phrasesHeight, dialogHeight)
                }
            }
        }
        .background(Color(.systemBackground))
        .edgesIgnoringSafeArea(.all)
        .onAppear {
            fetchPhraseGroups() // 从服务器获取常用词分组
        }
    }

    // 新增状态变量用于存储最大高度
    @State private var maxHeight: CGFloat = 0
    
    // 根结构：匹配服务器返回的完整JSON
    struct ServiceResponse<T: Codable>: Codable {
        let code: Int
        let message: String
        let data: [T]  // 使用泛型 T 替代固定的 PhraseGroup
        let timestamp: Int64
        let executeTime: Int
    }
    
    // 匹配data数组中的单个常用词
    struct Phrase: Codable, Identifiable {
        let id: Int  // 接口返回的是整数类型
        let content: String  // 显示的文本内容
        let groupId: Int  // 所属分组ID（整数类型）
        let createBy: String?  // 可能为null，用可选类型
        let createDate: String?
        let updateBy: String?
        let updateDate: String?
        let deleteDate: String?
        let useCount: Int
        let subtitle: String?  // 副标题（可能为空字符串或null）
        let sort: Int?  // 排序字段（可能为null）
    }
    
    
    
    //匹配data数组中的单个分组
    struct PhraseGroup: Codable, Identifiable {
        let id: Int  // 注意接口返回的是Int类型（如14、15）
        let name: String
        let createBy: String?  // 可能为null，用可选类型
        let createDate: String?
        let updateBy: String?
        let updateDate: String?
        let deleteDate: String?
        let sort: Int
    }
    
    // 异步获取常用词分组数据
    private func fetchPhraseGroups() {
        guard let url = URL(string: "http://175.178.156.176:8092/api/phrases/listGroup") else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("your_token_here", forHTTPHeaderField: "token")
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error fetching phrase groups: \(error)")
                return
            }
            
            // 检查HTTP响应状态码
            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Invalid response status code")
                return
            }
            
            guard let data = data else {
                print("No data received")
                return
            }
            
            do {
                // 1. 先解码为完整的响应结构
                let response = try JSONDecoder().decode(ServiceResponse<PhraseGroup>.self, from: data)
                
                // 2. 检查接口返回的业务状态码（code=200表示成功）
                guard response.code == 200 else {
                    print("API error: \(response.message)")
                    return
                }
                
                // 3. 提取data数组并更新UI
                DispatchQueue.main.async {
                    self.phraseGroups = response.data  // response.data就是分组数组
                    if let firstGroup = response.data.first {
                        self.selectedGroupId = firstGroup.id  // 注意id是Int类型
                        self.fetchAllPhrases()  // 请求所有常用词列表数据
                    }
                }
            } catch {
                print("Failed to decode phrase groups: \(error)")
                // 打印原始JSON帮助调试
                if let jsonString = String(data: data, encoding: .utf8) {
                    print("Received JSON: \(jsonString)")
                }
            }
        }.resume()
    }

    // 异步获取所有常用词列表数据
    private func fetchAllPhrases() {
        guard let url = URL(string: "http://175.178.156.176:8092/api/phrases/list") else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("your_token_here", forHTTPHeaderField: "token")
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error fetching all phrases: \(error)")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Invalid response status code")
                return
            }
            
            guard let data = data else {
                print("No data received")
                return
            }
            
            do {
                // 使用 ServiceResponse<Phrase> 解析常用词列表
                let response = try JSONDecoder().decode(ServiceResponse<Phrase>.self, from: data)
                
                guard response.code == 200 else {
                    print("API error: \(response.message)")
                    return
                }
                
                DispatchQueue.main.async {
                    self.allPhrases = response.data  // 正确解析为 [Phrase]
                    if let selectedGroupId = self.selectedGroupId {
                        self.filterPhrases(for: selectedGroupId)
                    }
                }
            } catch {
                print("Failed to decode all phrases: \(error)")
                if let jsonString = String(data: data, encoding: .utf8) {
                    print("Received JSON: \(jsonString)")
                }
            }
        }.resume()
    }

    // 根据分组ID筛选常用词列表
    private func filterPhrases(for groupId: Int) {
        self.phrases = self.allPhrases.filter { $0.groupId == groupId }
    }

    // 模拟数据 - 实际应用中应从服务器获取
    private func loadMockData() {
        // 模拟对话列表
        dialogItems = [
            DialogItem(id: "1", content: "1"),
            DialogItem(id: "2", content: "2"),
            DialogItem(id: "3", content: "3"),
            DialogItem(id: "4", content: "4"),
            DialogItem(id: "5", content: "5"),
            DialogItem(id: "6", content: "6"),
            DialogItem(id: "7", content: "7"),
            DialogItem(id: "8", content: "8"),
            DialogItem(id: "9", content: "9")
        ]
    }
    
    // 常用词视图
    var phrasesView: some View {
        VStack(spacing: 5) {
            // 分组选择区域
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 10) {
                    ForEach(phraseGroups) { group in
                        Button(action: {
                            selectedGroupId = group.id
                            filterPhrases(for: group.id)  // 直接从 allPhrases 中筛选数据
                        }) {
                            Text(group.name)
                                .padding(.horizontal, 12)
                                .padding(.vertical, 6)
                                .background(selectedGroupId == group.id ? Color.blue.opacity(0.3) : Color(.systemGray6))
                                .cornerRadius(5)
                                .foregroundColor(.black)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                .padding(.horizontal, 5)
            }
            .frame(height: 40)
            
            // 常用词列表
            ScrollView {
                VStack(spacing: 8) {
                    ForEach(phrases) { phrase in
                        Button(action: {
                            proxy.insertText(phrase.content)
                        }) {
                            Text(phrase.content)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .padding(8)
                                .background(Color(.systemGray6))
                                .cornerRadius(5)
                                .foregroundColor(.black)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                .padding(.horizontal, 5)
            }
            
        }
    }
    
    // 语境对话视图
    var dialogView: some View {
        VStack(spacing: 5) {
            // 对话内容显示区域
            ZStack(alignment: .topLeading) {
                if currentDialog.isEmpty {
                    Text("选择下方数字键插入对话")
                        .foregroundColor(.gray)
                        .padding()
                } else {
                    Text(currentDialog)
                        .padding()
                        .foregroundColor(.black)
                }
                
                Rectangle()
                    .stroke(Color(.systemGray4), lineWidth: 1)
                    .background(Color(.systemGray6))
            }
            .frame(height: 80)
            .padding(.horizontal, 5)
            
            // 粘贴按钮
            Button(action: {
                if !currentDialog.isEmpty {
                    proxy.insertText(currentDialog)
                    //keyboardMode = .normal // 插入后返回普通键盘
                }
            }) {
                Text("粘贴")
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 8)
                    .background(Color(.systemGray4))
                    .cornerRadius(5)
                    .foregroundColor(.black)
            }
            .buttonStyle(PlainButtonStyle())
            .padding(.horizontal, 5)
            .disabled(currentDialog.isEmpty)
            
            // 九宫格数字键盘
            HStack(spacing: 5) {
                // 左侧九宫格
                VStack(spacing: 5) {
                    ForEach(0..<3) { row in
                        HStack(spacing: 5) {
                            ForEach(0..<3) { col in
                                let index = row * 3 + col
                                if index < dialogItems.count {
                                    Button(action: {
                                        currentDialog = dialogItems[index].content
                                    }) {
                                        Text(dialogItems[index].content)
                                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                                            .background(Color(.systemGray5))
                                            .cornerRadius(5)
                                            .foregroundColor(.black)
                                    }
                                    .buttonStyle(PlainButtonStyle())
                                } else {
                                    Rectangle()
                                        .fill(Color.clear)
                                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                                }
                            }
                        }
                    }
                }
                .frame(maxWidth: .infinity)
                
                // 右侧功能键
                VStack(spacing: 5) {
                    Button(action: {
                        currentDialog = ""
                    }) {
                        Text("删除")
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .background(Color(.systemGray4))
                            .cornerRadius(5)
                            .foregroundColor(.black)
                    }
                    .buttonStyle(PlainButtonStyle())
                    
                    Button(action: {
                        if !currentDialog.isEmpty {
                            proxy.insertText(currentDialog)
//                            keyboardMode = .normal // 插入后返回普通键盘
                        }
                    }) {
                        Text("发送")
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .background(Color.blue.opacity(0.7))
                            .cornerRadius(5)
                            .foregroundColor(.white)
                    }
                    .buttonStyle(PlainButtonStyle())
                    .disabled(currentDialog.isEmpty)
                }
                .frame(width: 60)
            }
            .frame(height: 150)
            .padding(.horizontal, 5)
           
        }
    }
    
}
